<?php

namespace App\Imports;

use App\Http\Util\Tool;
use App\Models\AllExam;
use App\Models\OperAnswers;
use App\Models\OperateCate;
use App\Models\OperScore;
use App\Models\Question;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Illuminate\Support\Collection;

class OperScoreImport implements ToCollection
{

    public $all_exam_id;

    public function __construct($all_exam_id)
    {
        $this->all_exam_id = $all_exam_id;
    }

    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */
    public function collection(Collection $rows)
    {
        try{
            $operateId = AllExam::where('id',$this->all_exam_id)->value('operate_id');
//            $proIds =OperateCate::where('pid',$operateId)->get(['id'])->toArray();
            // TODO: Implement collection() method.
            //解析excel中的数据
            $proIds = [];
            $data=json_decode(json_encode($rows),true);
            foreach($data[0] as $k => $v){
                if(trim($v) != '代号') {
                    $proIds[$k] = OperateCate::where('pid', $operateId)
                        ->where('type', 2)
                        ->where('name', trim($v))
                        ->value('id');
                    if (!$proIds[$k]) {
                        return response()->json(['code' => 1002, '该考试无此项目信息']);
                    }
                }
            }
            //去掉第一行的标题
            array_splice($data, 0, 1);
            $log = '';
            //拼接字段入库
            foreach ($data as $row)
            {
                foreach($row as $k => $v){
                    if($k == 0){
                        if(!trim($v)){
                            break;
                        }
                        $save['operate_student_id'] = OperAnswers::where('alias',trim($v))
                            ->where('all_exam_id',$this->all_exam_id)->value('operate_student_id');
                    }else{
                        $save['cate_id']=$proIds[$k];
                        $save['all_exam_id'] = $this->all_exam_id;
                        $save['score'] = $v;
                        $checkId = OperScore::where('cate_id',$proIds[$k])
                            ->where('all_exam_id',$this->all_exam_id)
                            ->where('operate_student_id',$save['operate_student_id'])
                            ->value('id');
                        if($checkId){
                            OperScore::where('id',$checkId)->update($save);
                        }else{
                            OperScore::create($save);
                        }
                    }
                }
            }
        }catch (\Exception $e){
            echo $e->getMessage();
//                    Tool::logError('数据导入失败',$e->getMessage(), $file = 'lumen');
        }
    }


    public function createData($rows)
    {
        //todo
    }
}
